/**
* @file utils/apiCreator
* @author maoquan(maoquan@htsc.com)
*/

import request from './request';

import config from '../config/request';
import { queryToString } from './helper';
/**
 * api生成器
 *
 * @return {Fucntion}
 */


export default function createApi() {
	if (location.href.indexOf('token') > -1) {
		const url = location.href.toString();
		const arrUrl = url.split('?');
		var token = arrUrl[1].split('#')[0].slice(6);
	} else {
		var token = '';
	}
	const { prefix } = config;
	// 如果没有前缀，自动补上
	const padPrefix = (url) => {
		if (url.indexOf(prefix) === -1) {
			return prefix + url;
		}
		return url;
	};

	return {

		/**
		 * @param {string} url API url
		 * @param {Object} query 请求参数
		 *
		 * @return {Promise}
		 */
		get(url, query) {
			const finalUrl = padPrefix(url);
			const queryString = queryToString(query);
			return request(
				`${finalUrl}?${queryString}`,
				{
					method: 'GET',
					headers: {

						Authorization: token,
					},
				},
			);
		},

		/**
		 * @param {string} url API url
		 * @param {Object} query 请求参数
		 *
		 * @return {Promise}
		 */
		post(url, query) {
			const finalUrl = padPrefix(url);
			return request(
				finalUrl,
				{
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
						Authorization: token,
					},
					body: JSON.stringify(query),
				},
			);
		},

		put(url, query) {
			const finalUrl = padPrefix(url);
			return request(
				finalUrl,
				{
					method: 'PUT',
					headers: {
						'Content-Type': 'application/json',
						Authorization: token,
					},
					body: JSON.stringify(query),
				},
			);
		},

		delete(url, query) {
			const finalUrl = padPrefix(url);
			return request(
				finalUrl,
				{
					method: 'DELETE',
					headers: {
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
						Authorization: token,
					},
					body: JSON.stringify(query),
				},
			);
		},

		/**
		* @param {string} url 神策日志接收服务器url
		* @param {Object} query 日志参数
		*
		* @return {Promise}
		*/
		sendLog(url, query) {
			return request(
				url,
				{
					method: 'POST',
					body: JSON.stringify(query),
				},
			);
		},
	};
}
